package com.sgb.knowledgeshare.view.activity;


import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.TextView;
import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.ViewModelProvider;
import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.sgb.knowledgeshare.weight.SlideBackActivity;
import com.sgb.knowledgeshare.R;
import com.sgb.knowledgeshare.databinding.FragmentShareVideoplayListBinding;
import com.sgb.knowledgeshare.viewmodel.PlayListModelModel;
import com.sgb.knowledgeshare.weight.AlivcVideoListView;
import com.sgb.knowledgeshare.weight.AlivcVideoPlayView;
import com.sgb.knowledgeshare.weight.CommentDialog;
import com.sgb.knowledgeshare.weight.CommentSendDialog;
import com.sgb.knowledgeshare.weight.ControllerView;
import com.swgk.core.base.aroute.AppRouteConstant;
import com.swgk.core.base.model.entity.VideoBean;
import com.sgb.knowledgeshare.utils.OnVideoControllerListener;
import com.swgk.core.event.EventConstant;
import com.swgk.core.event.MenuEvent;
import com.swgk.core.dialog.RoundCornerDialog;
import com.sgb.knowledgeshare.weight.ShareDialog;
import com.swgk.core.util.MToast;
import com.swgk.core.util.SharedPreferenceUtil;
import com.swgk.core.view.entity.VideoListEntity;

import org.greenrobot.eventbus.EventBus;
import java.util.List;

/**
 * 全屏播放
 */
@Route(path = AppRouteConstant.PLAYLIST_ACTIVITY)
public class PlayListActivity extends SlideBackActivity {
    PlayListModelModel viewmodel;
    private FragmentShareVideoplayListBinding binding;
    /**
     * 加载视频的类型(分享-分类、商品-大首页、分享-用户中心)
     * fX_classify分享分类
     */
    public static String VIDEOTYPE = "videotype";
    /**
     * 播放视频的角标
     */
    public static String PSO = "pso";

    /**
     * 视频数据源
     */
    public static String VIDEOLISTBEAN = "video_list_bean";
    /**
     * 用户userno
     */
    public static String USERNO = "userno";
    /**
     * tab一级分类名称
     */
    public static String VIDEOTITLE = "video_one_title";

    private boolean homeVideoDelete;
    /**
     * 页码
     */
    public static String PAGE = "page";
    private int videoPos;
    private List<VideoBean> bean;
    private String typeNo;
    private int page = 0;
    private List<VideoBean> adapterList;
    private String userNo;
    private String userType;
    /**
     * 用户操作区域显示
     */
    public static String IS_ShOW_USER = "isShowUser";
    private boolean isShowUser = true;
    private String labelNo;
    private String videoType;
    private int homesPages;

    @Autowired(name = "videotype")
    public String videotypes;
    @Autowired(name = "pso")
    public int psos;
    @Autowired(name = "page")
    public int pages;
    @Autowired(name = "isARouter")
    public boolean isARouter;
    @Autowired(name = "data")
    public String records;
    private String videoTypes = "";

    @Override
    protected void initView() {
        binding = DataBindingUtil.setContentView(this, R.layout.fragment_share_videoplay_list);
        viewmodel = new ViewModelProvider(this).get(PlayListModelModel.class);
        viewmodel.setActivity(PlayListActivity.this);
        binding.videoPlayDetailView.setShowComment(true);
        binding.backView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (getIntent().getStringExtra(PlayListActivity.VIDEOTYPE).equals("home_bigVideo")) {
                    SendHomeVideoServer();
                }
                finish();
            }
        });
        binding.videoPlayDetailView.setOnRefreshDataListener(new AlivcVideoListView.OnRefreshDataListener() {
            @Override
            public void onRefresh() {
                if (adapterList != null && adapterList.size() > 0) {
                    binding.videoPlayDetailView.refreshVideoList(adapterList);
                }
            }

            @Override
            public void onLoadMore() {
                getLoadMoreData();
            }
        });
        binding.videoPlayDetailView.setCallback(new AlivcVideoPlayView.UserVideoCallback() {
            @Override
            public void UserVideoController(ControllerView controller, VideoBean videoBean) {
                //视频右下角按钮点击事件处理
                likeShareEvent(controller);
            }

            @Override
            public void VideoInfo(int pos, VideoBean video) {
                //添加播放次数
                viewmodel.getplayVideo(video.getVideoId());
            }

            @Override
            public void UserVideoLike(VideoBean bean, ControllerView controller) {
                //点赞
                viewmodel.setLike(bean.getVideoId() + "");
                setShuangJiDianZan(bean, controller);
            }
        });
    }

    /**
     * 不同type加载更多处理
     */
    private void getLoadMoreData() {
        if (isARouter) {
            page = pages;
            videoTypes = videotypes;
        } else {
            if (TextUtils.isEmpty(getIntent().getStringExtra(PlayListActivity.VIDEOTYPE))) return;
        }
        page++;
        switch (videoTypes) {
            case "fX_classify"://分享分类
                viewmodel.getVideoTypeList(page, typeNo);
                break;
            case "fx_mine":
                viewmodel.getVideoListData(page, userNo, userType);
                break;
            case "home_bigVideo":
                // if (page<=homesPages){
                viewmodel.getHomeVideoListData(page, videoType);
             /*   }else {
                    MToast.showToast(getActivity(), "没有更多视频数据啦！");
                }*/
                break;
            case "fx_bighomechild":
                //viewmodel.getHomeVideoListData(page,videoType);
                break;
            case "fX_label":
                viewmodel.getVideLabelPage(page, labelNo);
                break;
            //货源列表页和找车界面播放视频,不能loadMore
            case "goods_and_car_video":
                break;
            case "home_lease":
//                viewmodel.getVideo(page);
                break;
            case "home_jicai":
                homeJiCaiData(page);
                break;
            case "home_zhaocai":
                viewmodel.memberVideoShare(page);
                break;

        }
    }

    private void homeJiCaiData(int page) {
        viewmodel.getVideoList(page);
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //  EventBus.getDefault().postSticky(this);
    }

    @Override
    protected void init() {
        if (isARouter) {
            videoTypes = videotypes;
            videoPos = psos;
        } else {
            if (TextUtils.isEmpty(getIntent().getStringExtra(PlayListActivity.VIDEOTYPE))) return;
            //共同的字段值获取
            videoPos = getIntent().getIntExtra(PSO, 0);
            videoTypes = getIntent().getStringExtra(PlayListActivity.VIDEOTYPE);
        }
        isShowUser = getIntent().getBooleanExtra(IS_ShOW_USER, true);
        //根据不通分类获取不通的字段信息
        switch (videoTypes) {
            case "fX_classify"://分类
                page = getIntent().getIntExtra(PAGE, 0);
                typeNo = getIntent().getStringExtra(VIDEOTITLE);
                VideoBeanData();
                break;
            case "fx_mine"://用户中心
                page = getIntent().getIntExtra(PAGE, 0);
                userNo = getIntent().getStringExtra(USERNO);
                userType = getIntent().getStringExtra(VIDEOTITLE);
                VideoBeanData();
                break;
            case "home_bigVideo"://首页
                getHomeVideoBean();
                break;
            case "fx_bighomechild"://这个分类没有启用
                //  getHomeVideoBean();
                break;
            case "fX_label"://标签详情
                page = getIntent().getIntExtra(PAGE, 0);
                labelNo = getIntent().getStringExtra(VIDEOTITLE);
                VideoBeanData();
                break;
            case "goods_and_car_video":
                bean = (List<VideoBean>) getIntent().getSerializableExtra(VIDEOLISTBEAN);
                binding.videoPlayDetailView.refreshVideoList(bean, videoPos);
                break;
            case "website_video":
                VideoWebsiteInfoBeanData();
                break;
            case "home_lease":
                bean = (List<VideoBean>) getIntent().getSerializableExtra(VIDEOLISTBEAN);
                binding.videoPlayDetailView.refreshVideoList(bean, videoPos);
                break;
            case "home_jicai":
            case "home_zhaocai":
                if (isARouter) {
                    page = pages;
                } else {
                    page = getIntent().getIntExtra(PAGE, 0);
                }
                VideoBeanData();
                break;
        }

    }

    //首页过来的视频数据
    private void getHomeVideoBean() {
        StringBuilder sb = new StringBuilder();
        bean = (List<VideoBean>) getIntent().getSerializableExtra(VIDEOLISTBEAN);
        for (VideoBean videoBean : bean) {
            sb.append(videoBean.getVideoId());
        }
        //Log.e("tag字符串",sb.toString() );
        homeVideoDelete = true;
        videoType = getIntent().getStringExtra(VIDEOTITLE);
        page = 1;
        viewmodel.getHomeVideoListData(page, videoType);
    }

    //分享模块过来的数据
    private void VideoBeanData() {
        if (isARouter){
            bean = new Gson().fromJson(records, new TypeToken<List<VideoBean>>() {
            }.getType());
            if (null == bean) return;
            binding.videoPlayDetailView.refreshVideoList(bean, videoPos);
        }else {
            bean = (List<VideoBean>) getIntent().getSerializableExtra(VIDEOLISTBEAN);
            if (null == bean) return;
            binding.videoPlayDetailView.refreshVideoList(bean, videoPos);
        }
        adapterList = binding.videoPlayDetailView.getAdapterList();
        binding.videoPlayDetailView.setShowUser(isShowUser);
    }

    //个人中心网店模块过来的数据
    private void VideoWebsiteInfoBeanData() {
        binding.videoPlayDetailView.setOnRefreshDataListener(null);
        bean = (List<VideoBean>) getIntent().getSerializableExtra(VIDEOLISTBEAN);
        if (null == bean) return;
        binding.videoPlayDetailView.refreshVideoList(bean, videoPos);
        adapterList = binding.videoPlayDetailView.getAdapterList();
        binding.videoPlayDetailView.setShowUser(isShowUser);
    }

    private void likeShareEvent(ControllerView controller) {
        controller.setListener(new OnVideoControllerListener() {
            //点赞
            @Override
            public void onLikeClick(VideoBean data) {
                viewmodel.setLike(data.getVideoId() + "");
                setDianZan(data, controller);
            }

            //点击分享的事件处理
            @Override
            public void onShareClick(VideoBean videoData) {
                new ShareDialog(PlayListActivity.this, 2, videoData).setOnDeleteVideo(new ShareDialog.OnDeleteVideo() {
                    @Override
                    public void OnDeleteVideoData(int Id) {
                        DeleteVideo(Id);
                    }
                });
            }

            // 点击头像下面的+号事件处理
            @Override
            public void onFocusClick(VideoBean videoData) {
                if (SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.USER_NO, "").equals(videoData.getCreateUser())) {
                    MToast.showToast(getActivity(), "不能关注自己的视频");
                } else {
                    viewmodel.getFens(videoData.getCreateUser());
                    setGuanzhu(videoData, controller);
                }
            }

            // 点击头像的事件处理
            @Override
            public void onHeadClick(VideoBean videoData) {
                if (SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.USER_NO, "").equals(videoData.getCreateUser())) {
                    finish();
                } else {
                    ShareUserActivity.start(getActivity(), videoData.getCreateUser());
                }
            }

            //评论
            @Override
            public void onCommentClick(VideoBean videoData) {
                new CommentDialog(PlayListActivity.this, videoData, "0", 1, 1).setonDialog(new CommentDialog.HiedDialog() {
                    @Override
                    public void onhiedDialog() {
                        viewmodel.getCommentNum(videoData, controller);
                    }
                });
            }

            //直评实现
            @Override
            public void onCommentSend(VideoBean videoBean) {
                new CommentSendDialog(PlayListActivity.this, videoBean).setCommentsucceed(new CommentSendDialog.CommentSucceed() {
                    @Override
                    public void OnCommentNumber() {
                        viewmodel.getCommentNum(videoBean, controller);
                    }
                });
            }

            //点击页签跳转
            @Override
            public void onLabelClickListener(VideoBean videoData) {
                LabelDetailsActivity.start(getApplicationContext(), videoData.getLabelName(), videoData.getLabelNo());
            }
        });
    }

    private void setDianZan(VideoBean bean, ControllerView controller) {
        if (bean.isLiked()) {//为点赞
            int laudCountq = bean.getLaudCount();
            if (laudCountq != 0) {
                laudCountq--;
            }
            bean.setLiked(false);
            bean.setLaudCount(laudCountq);
        } else {
            int laudCountd = bean.getLaudCount();
            laudCountd++;
            bean.setLaudCount(laudCountd);
            bean.setLiked(true);
        }
        controller.like();
        controller.setVideoData(bean, getApplicationContext(), true);
    }

    private void setGuanzhu(VideoBean bean, ControllerView controller) {
        if (bean.getIsFollow() == 1) {//为关注
            bean.setIsFollow(0);
        } else {//没有关注
            bean.setIsFollow(1);
        }
        controller.setVideoData(bean, getApplicationContext(), true);
    }

    //    删除视频的操作
    private void DeleteVideo(int id) {
        View view = View.inflate(getActivity(), R.layout.dialog_two_btn, null);
        final RoundCornerDialog roundCornerDialog = new RoundCornerDialog(getActivity(), 0, 0, view, R.style.RoundCornerDialog);
        roundCornerDialog.show();
        roundCornerDialog.setCanceledOnTouchOutside(false);// 设置点击屏幕Dialog不消失
        TextView tv_message = view.findViewById(R.id.tv_message);
        TextView tv_logout_confirm = view.findViewById(R.id.tv_logout_confirm);
        TextView tv_logout_cancel = view.findViewById(R.id.tv_logout_cancel);
        tv_message.setText("您的作品将被永久删除，无法找回。确认删除？");
        //确定
        tv_logout_confirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //删除视频的操作逻辑
                roundCornerDialog.dismiss();
                viewmodel.deleteMyVideo(id);
            }
        });
        //取消
        tv_logout_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                roundCornerDialog.dismiss();
            }
        });
    }

    private void setShuangJiDianZan(VideoBean bean, ControllerView controller) {
        if (bean.isLiked()) {
            int laudCountd = bean.getLaudCount();
            if (laudCountd > 0) {
                laudCountd--;
            }
            bean.setLaudCount(laudCountd);
            bean.setLiked(false);
        } else {
            int laudCountd = bean.getLaudCount();
            laudCountd++;
            bean.setLaudCount(laudCountd);
            bean.setLiked(true);
        }
        controller.like();
        controller.setVideoData(bean, getActivity(), true);
    }

    public void setVideoTypeList(List<VideoBean> records) {
        if (records.size() > 0) {
            binding.videoPlayDetailView.addMoreData(records);
        } else {
            MToast.showToast(getActivity(), "没有视频数据啦！");
        }
        adapterList = binding.videoPlayDetailView.getAdapterList();
    }

    /**
     * 删除视频后的操作处理
     *
     * @param id
     */
    public void setDeleteList(int id) {
        if (adapterList.size() > 1) {
            int cur = -1;
            for (int i = 0; i < adapterList.size(); i++) {
                if (adapterList.get(i).getId() == id) {
                    if (i > 3 && getIntent().getStringExtra(PlayListActivity.VIDEOTYPE).equals("home_bigVideo")) {
                        homeVideoDelete = false;
                        SendHomeVideoServer();
                    }
                    cur = i;
                }
            }
            if (cur != -1) {
                adapterList.remove(cur);
                if (cur < adapterList.size()) {
                    binding.videoPlayDetailView.refreshVideoList(adapterList, cur);
                } else {
                    binding.videoPlayDetailView.refreshVideoList(adapterList, cur - 1);
                }
            }
        } else {
            if (getIntent().getStringExtra(PlayListActivity.VIDEOTYPE).equals("home_bigVideo")) {
                SendHomeVideoServer();
            }
            finish();
        }
    }

    private void SendHomeVideoServer() {
        if (homeVideoDelete == false) {
            //发送广播到首页更新数据信息
            EventBus.getDefault().postSticky(MenuEvent.make().setMessageTag(EventConstant.EVENT_HOME_PLAY_VIDEOLIST));
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        binding.videoPlayDetailView.onResume();
    }

    @Override
    public void onPause() {
        super.onPause();
        binding.videoPlayDetailView.onPause();
    }

    @Override
    public void onDestroy() {
        binding.videoPlayDetailView.onDestroy();
        super.onDestroy();
    }

    public void setCommentNum(VideoBean videoData, ControllerView controllerView) {
        controllerView.setVideoData(videoData, getActivity(), true);
    }

    public void setHomeVideoListData(VideoListEntity data) {
        //homesPages = data.getPages();
        if (data.getRecords() == null) return;
        if (data.getRecords().size() > 0) {
            if (data.getPages() > 1) {
                binding.videoPlayDetailView.addMoreData(data.getRecords());
            } else {
                binding.videoPlayDetailView.refreshVideoList(data.getRecords(), videoPos);
            }
        } else {
            MToast.showToast(getActivity(), "没有视频数据啦！");
        }
        adapterList = binding.videoPlayDetailView.getAdapterList();
    }
}
